# PowerShell脚本用于构建和运行优化的HFT系统

# 设置错误操作
$ErrorActionPreference = "Stop"

# 定义颜色函数
function Write-ColorOutput($ForegroundColor) {
    $fc = $host.UI.RawUI.ForegroundColor
    $host.UI.RawUI.ForegroundColor = $ForegroundColor
    if ($args) {
        Write-Output $args
    }
    $host.UI.RawUI.ForegroundColor = $fc
}

# 创建构建目录
Write-ColorOutput Green "创建构建目录..."
$buildDir = "build"
if (!(Test-Path $buildDir)) {
    New-Item -ItemType Directory -Path $buildDir | Out-Null
}

# 检查是否安装了CMake
try {
    $cmakeVersion = cmake --version
    Write-ColorOutput Green "检测到CMake版本: $cmakeVersion"
}
catch {
    Write-ColorOutput Red "错误: 未找到CMake。请安装CMake并确保它在系统PATH中。"
    exit 1
}

# 检查是否安装了Visual Studio
$vsWhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
if (Test-Path $vsWhere) {
    $vsPath = & $vsWhere -latest -property installationPath
    if ($vsPath) {
        Write-ColorOutput Green "检测到Visual Studio安装路径: $vsPath"
    }
    else {
        Write-ColorOutput Red "错误: 未找到Visual Studio安装。"
        exit 1
    }
}
else {
    Write-ColorOutput Red "错误: 未找到Visual Studio。请安装Visual Studio 2019或更高版本。"
    exit 1
}

# 进入构建目录
Push-Location $buildDir

try {
    # 配置CMake项目
    Write-ColorOutput Green "配置CMake项目..."
    cmake -G "Visual Studio 17 2022" -A x64 ..
    if ($LASTEXITCODE -ne 0) {
        throw "CMake配置失败"
    }

    # 构建Release版本
    Write-ColorOutput Green "构建Release版本..."
    cmake --build . --config Release
    if ($LASTEXITCODE -ne 0) {
        throw "构建失败"
    }

    # 运行测试
    Write-ColorOutput Green "运行测试..."
    $testExe = ".\bin\Release\optimized_system_test.exe"
    if (Test-Path $testExe) {
        & $testExe
        if ($LASTEXITCODE -ne 0) {
            throw "测试失败"
        }
    }
    else {
        throw "未找到测试可执行文件: $testExe"
    }

    # 运行性能测试
    Write-ColorOutput Green "运行性能测试..."
    cmake --build . --target performance_test --config Release
    if ($LASTEXITCODE -ne 0) {
        throw "性能测试失败"
    }

    # 生成文档（如果安装了Doxygen）
    $doxygen = Get-Command doxygen -ErrorAction SilentlyContinue
    if ($doxygen) {
        Write-ColorOutput Green "生成文档..."
        cmake --build . --target docs
        if ($LASTEXITCODE -ne 0) {
            Write-ColorOutput Yellow "警告: 文档生成失败"
        }
    }
    else {
        Write-ColorOutput Yellow "警告: 未找到Doxygen，跳过文档生成"
    }

    # 输出成功消息
    Write-ColorOutput Green "`n构建和测试成功完成！"
    Write-ColorOutput Green "可执行文件位置: $testExe"
    
    # 显示性能测试结果摘要
    if (Test-Path "performance_results.txt") {
        Write-ColorOutput Cyan "`n性能测试结果摘要:"
        Get-Content "performance_results.txt" | ForEach-Object {
            Write-ColorOutput White $_
        }
    }

}
catch {
    Write-ColorOutput Red "`n错误: $_"
    exit 1
}
finally {
    # 返回原始目录
    Pop-Location
}

# 等待用户按键
Write-ColorOutput Green "`n按任意键退出..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")